/*
 * Camacho_Jose_DA3.c
 *  Author: camach28
 */ 


#include <avr/interrupt.h>
#include <avr/io.h>
 

volatile uint8_t t1FallingCount = 0;  //Falling Edges count

//------------------------------Normal Mode for counter 0 with clock on falling edge-------
void SetCount0()   
{
	TCCR0A = 0x00;
	TCCR0B = 0x06;
	
}

//------------------------------Output of counter 0---------------------------------
void Count0out()
{
	PORTC = (PORTC & 0xC0) | (0x3F & TCNT0);
	PORTB = (PORTB & 0x3F) | (0xC0 & TCNT0);	
}

 
//-------------------------------Count of Falling Edge-----------------------------
 
void FallingEdge() 
{  
	 if((PINB&(1<<1)) == 0)
		{
			t1FallingCount++; //At this point we increment the Falling Count.
 
 
 //-----------------------------When the falling edge count gets to 16, need to toggle and reset.-----             
                if(t1FallingCount == 16)
				{
                        t1FallingCount = 0;
				        PORTB ^= 1;
				}
        }
}
 
//----------------------ISR will call Falling Edge and Counter 0 functions---------------
 ISR(TIMER1_COMPA_vect)
 {
        FallingEdge();
        Count0out();
}
 
//-------------------------Timer 1 will be turned on here------------------
 
void Timer1On()
{
        TCNT1 = 0;    //Reset the Timer
        OCR1A = 3906; // Make sure timer resets after given time of 125ms
        TIMSK1 = 0x02;//Timer1 interrupt will be set for Compare A.
        
//--------Set prescaler at 256, toggle the compare.--------------------
		TCCR1A = 0x40;
        TCCR1B = 0x0C;
        TCCR1C = 0x00;
 }
 

//-------------------Main --------------------------------------------------------
int main(void)
 
{
 
//--------Set Input and Output-------------------------------------------------------
 
        DDRB =  0xC3;
        DDRC =  0x3F;
        DDRD =  0x00; 
        PORTD = 0x14;
 
 //--------------Enable the Interrupts and Timers------------------------------------       
        sei();
        SetCount0();
        Timer1On();
		
 
        while(1);
 
} 
